#include <iostream>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <errno.h>
#include <cstring>
#include <cstdlib>
#include <stdio.h>
#define NUM 5
typedef void(*func_t)(); // 定义一个函数指针类型
func_t task[NUM]; // 定义一个函数指针数组
void task1() {
    std::cout << "Task 1 is running." << std::endl;
}
void task2() {
    std::cout << "Task 2 is running." << std::endl;
}
void task3() {
    std::cout << "Task 3 is running." << std::endl;
}
void task4() {
    std::cout << "Task 4 is running." << std::endl;
}
void task5() {
    std::cout << "Task 5 is running." << std::endl;
}       
void initTask() {
    task[0] = task1;
    task[1] = task2;
    task[2] = task3;
    task[3] = task4;
    task[4] = task5;
}
void run() {
    for (int i = 0; i < NUM; ++i) {
        task[i]();
    }
}

int main() {
    initTask(); // Initialize the task array
    pid_t pid = fork();
    if (pid < 0) {
        // Fork failed
        perror("fork");
        return 1;
    } else if (pid == 0) {
        // Child process
        std::cout << "Child process running with PID: " << getpid() << std::endl;
        sleep(2); // Simulate some work in the child process
        std::cout << "Child process exiting." << std::endl;
        return 0;
    } else {
        // Parent process
        std::cout << "Parent process waiting for child process (non-blocking)." << std::endl;
        int status;
        pid_t result;
        do {
            result = waitpid(pid, &status, WNOHANG);
            if (result == 0) {
                run();
                sleep(1); // Simulate doing other work
            } else if (result == -1) {
                perror("waitpid");
                return 1;
            }
        } while (result == 0);

        if (WIFEXITED(status)) {
            std::cout << "Child process exited with status: " << WEXITSTATUS(status) << std::endl;
        } else {
            std::cout << "Child process did not exit normally." << std::endl;
        }
    }

    return 0;
}